package com.stsdai.search.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.stsdai.common.pojo.StsdaiResult;
import com.stsdai.manager.pojo.Item;
import com.stsdai.search.service.SearchService;


@Controller
@RequestMapping("search")
public class SearchController {
	
	@Autowired
	private SearchService searchService;

	@Value("${SEARCH_STSDAI_ITEM_ROWS}")
	private Integer rows;

	// http://search.stsdai.com/search.html?q=apple
	/**
	 * 根据条件分页查询商品
	 * 
	 * @param model
	 * @param q
	 * @param page
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String search(Model model, String q, @RequestParam(value = "page", defaultValue = "1") Integer page) {

		// 解决get请求的乱码问题
		try {
			 q = new String(q.getBytes("ISO-8859-1"), "UTF-8");
			//q = new String(q.getBytes("ISO-8859-1"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 使用搜索服务查询商品数据
		StsdaiResult<Item> stsdaiResult = this.searchService.search(q, page, this.rows);

		// 把数据放到Model中，传递给前台页面
		// 搜索关键字
		model.addAttribute("query", q);
		// 商品列表
		model.addAttribute("itemList", stsdaiResult.getRows());
		// 当前页码数
		model.addAttribute("page", page);
		// 总页数(total+rows-1)/rows
		model.addAttribute("totalPages", (stsdaiResult.getTotal() + this.rows - 1) / this.rows);

		return "search";
	}

}
